import { View } from "@tarojs/components";
import React, { Children, useState } from "react";

interface MenuProps {
  defaultIndex?: number;
  change?: (index: number, menu?: string | number, args?: any) => void; // 点击菜单项的回调函数
  bar?: boolean;
  barColor?: string;
  children?: React.ReactNode;
  className?: string;
  type?: "center" | "left" | "right";
}

interface ItemProps {
  title: string;
  children?: React.ReactNode;
  className?: string;
}

function ScrollMenu({
  change,
  bar,
  defaultIndex = 0,
  children,
  className,
  type = "left",
}: MenuProps) {
  const [select, setSelect] = useState(defaultIndex);
  const menus =
    Children.map(
      children,
      (child) => (child as React.ReactElement<ItemProps>).props.title
    ) ?? [];

  function handle(i, menu) {
    console.log("handle");
    setSelect(i);
    change && change(i, menu);
  }
  return (
    <View className={className}>
      <View
        className="flex gap-3 w-full"
        style={{
          justifyContent:
            type === "center"
              ? "center"
              : type === "left"
              ? "flex-start"
              : "flex-end",
        }}
      >
        {menus.map((menu, i) => (
          <View
            onClick={() => handle(i, menu)}
            key={i}
            className={`w-10 flex justify-center items-center flex-col ${
              select == i ? "font-bold text-black " : ""
            }`}
          >
            {menu}
            {bar && (
              <View
                className={`"w-5 h-1 rounded-full mt-1 ${
                  select == i ? "bg-blue-400" : "transparent"
                }"`}
              ></View>
            )}
          </View>
        ))}
      </View>
      <View>
        {/* 根据当前选中的索引来渲染对应的子项内容 */}
        {Children.map(children, (child, idx) => {
          // 确保 child 是有效元素
          if (React.isValidElement(child) && idx === select) {
            return child; // 仅渲染当前选中的子项
          }
          return null; // 其他的返回 null
        })}
      </View>
    </View>
  );
}

ScrollMenu.Item = ({ title, children, className }: ItemProps) => {
  return <View className={className}>{children}</View>;
};

export default ScrollMenu;
